package day16;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;

/**
 * @author: 王丹
 * @create: 2021-07-23 13:47
 **/
public class Demo2 {

    /**
     * 效果和join实现的效果一样，代码中创建了计数器为2的 CountDownLatch，主线程中调用
     * countDownLatch.await();会让主线程等待，t1、t2线程中模拟执行耗时操作，最终在finally中调用了
     * countDownLatch.countDown();,此方法每调用一次，CountDownLatch内部计数器会减1，当计数器变
     * 为0的时候，主线程中的await()会返回，然后继续执行。注意：上面的 countDown()这个是必须要执行
     * 的方法，所以放在finally中执行。
     * @param args
     * @throws InterruptedException
     */
    public static void main(String[] args) throws InterruptedException {
        long starTime = System.currentTimeMillis();
        CountDownLatch countDownLatch = new CountDownLatch(2);
        T t1 = new T("解析sheet1线程", 2, countDownLatch);
        t1.start();
        T t2 = new T("解析sheet2线程", 5, countDownLatch);
        t2.start();
        countDownLatch.await();
        long endTime = System.currentTimeMillis();
        System.out.println("总耗时:" + (endTime - starTime));
    }

    public static class T extends Thread {
        int sleepSeconds;
        CountDownLatch countDownLatch;

        public T(String name, int sleepSeconds, CountDownLatch countDownLatch) {
            super(name);
            this.sleepSeconds = sleepSeconds;
            this.countDownLatch = countDownLatch;
        }

        public void run() {
            Thread ct = Thread.currentThread();
            long startTime = System.currentTimeMillis();
            System.out.println(startTime + "," + ct.getName() + ",开始处理!");
            try {
                TimeUnit.SECONDS.sleep((long) this.sleepSeconds);
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                countDownLatch.countDown();
            }
            long endTime = System.currentTimeMillis();
            System.out.println(endTime + "," + ct.getName() + ",处理完毕,耗时:" + (endTime - startTime));
        }
    }
}
